import java.util.Timer;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class TicTacToe extends MIDlet implements CommandListener {
	private Command exit;
	private Command start_game;

	private TextField name_field;
	private Form name_form;
	public GameBoard board;

	private Player me, them;
	char local_id = 0;
	String local_name = null;
	Timer timer = new Timer();
	MyClock mClock = null;

	private void init_username() {
		// initialize control info
		String ctl = MyRMS.get_control_info();
		System.out.println(ctl);
		if (ctl != null && ctl.trim().length() > 0) {

		}
	}

	public void received_cmd(byte[] cmd) {
		// receive a message from another phone

		if (cmd == null)
			return;

		String m = new String(cmd);
		if (cmd[0] == MyRMS.prog_mark) {

		}
	}

	public TicTacToe() {
		exit = new Command("Exit", Command.EXIT, 1);
		start_game = new Command("Start Game", Command.OK, 0);

		name_field = new TextField("Enter your name: ", "", 10, TextField.ANY);
		name_form = new Form("Tic Tac Toe");
		name_form.append(name_field);
		name_form.addCommand(exit);
		name_form.addCommand(start_game);
		name_form.setCommandListener(this);

		// decide player symbols
		me = new Player(true, 'X', this);
		them = new Player(false, 'O', this);

		// decide who goes first
		board = new GameBoard(me, them);
		board.setCommandListener(this);
		init_username();

	}

	protected void startApp() {
		MyRMS.reset_record();
		mClock = new MyClock(this);
		timer.schedule(mClock, 0, 500);

		Display.getDisplay(this).setCurrent(name_form);
	}

	public void commandAction(Command cmd, Displayable disp) {
		if (cmd == exit) {
			destroyApp(false);
			notifyDestroyed();
		} else if (cmd == start_game) {
			me.setName(name_field.getString());
			Display.getDisplay(this).setCurrent(board);
		} else if (cmd == board.yes) {
			board = new GameBoard(me, them);
			board.setCommandListener(this);
			Display.getDisplay(this).setCurrent(board);
		} else if (cmd == board.no){
			System.exit(0);
		}
	}

	protected void pauseApp() {
	}

	protected void destroyApp(boolean bool) {
	}
}
